
<template>
  <div class="caruser_box">
    <topHeader>
      <span slot="center">车主发布</span>
    </topHeader>
    <div class="caruser_layout">
      <div class="begin_city_box">
        <div class="dot"></div>
        <div class="title">出发城市</div>
        <div class="city" @click="choseCity(0)">{{ startCity }}</div>
      </div>
      <div class="end_city_box">
        <div class="dot"></div>
        <div class="title">结束城市</div>
        <div class="city" @click="choseCity(1)">{{ endCity }}</div>
      </div>
      <div class="help_call_box">
        <div class="help">
          <div><img src="./../../assets/img/clock.png" alt=""></div>
          <div>
            <Datetime
              v-model="postParam.outtime"
              format="YYYY-MM-DD HH:mm"
              @on-change="changeTime"
              :placeholder="'出发时间'"
              year-row="{value}年"
              month-row="{value}月"
              day-row="{value}日"
              hour-row="{value}点"
              minute-row="{value}分"
              confirm-text="完成"
              cancel-text="取消">
              </Datetime>
            </div>
          <!-- <div><input type="text" placeholder="请选择出发时间"></div> -->
        </div>
        <div class="call">
          <div><img src="./../../assets/img/people.png" alt=""></div>
          <div>
            <popup-picker
            :placeholder="'可乘坐人数'"
            :data="peopleNumList"
            v-model="peopleNum"
            @on-show="onShow"
            @on-hide="onHide"
            @on-change="onPeopleChange">
             </popup-picker>
          </div>
          <!-- <div><input type="text" placeholder="请选择人数"></div> -->
        </div>
      </div>
    </div>
    <div class="devide"></div>
    <div class="caruser_b">
      <div class="route">
        <div class="icon">
          <img src="./../../assets/img/route.png" alt="">
        </div>
        <div class="title">
          行驶路线
        </div>
      </div>
      <div class="route_input">
        <textarea v-model="routeTextarea"></textarea>
      </div>
      <div class="car_box">
        <div class="icon">
          <img src="./../../assets/img/car.png" alt="">
        </div>
        <div class="title">
          品牌车型
        </div>
        <div class="input_box">
          <input type="text" placeholder="例如：雪佛兰科鲁兹" v-model="carType">
        </div>
      </div>
      <div class="car_box">
        <div class="icon">
          <img src="./../../assets/img/pay.png" alt="">
        </div>
        <div class="title" style="width: 60%;">
          <popup-picker
            :placeholder="'乘客分摊费用'"
            :data="peopleFreeList"
            v-model="peopleMoney"
            @on-show="onShow"
            @on-hide="onHide"
            @on-change="onFreeChange">
             </popup-picker>
        </div>
        <div class="input_box">
          <!-- <input type="text" placeholder=""> -->
        </div>
      </div>
      <div class="route">
        <div class="icon">
          <img src="./../../assets/img/note.png" alt="">
        </div>
        <div class="title">
          备注
        </div>
      </div>
      <div class="note_input">
        <textarea v-model="noteTextarea"></textarea>
      </div>
      <!-- <div class="caruser_phone">
        <div class="phone_left">您的联系电话：138457891</div>
        <div class="btn">修改</div>
      </div> -->
      <div class="summit_btn" @click="sumit">
        发布行程
      </div>
      <div class="user_laws">
          <div class="user_laws_l">
              <input class="aui-radio" type="checkbox" name="demo1" value="1" v-model="agree" >我已阅读并同意人人同行顺风车
              <span class="user_laws_r" @click="OpenAbout">用户协议</span>
          </div>
      </div>
    </div>
    <popup v-model="cityShow" position="bottom" width="100%" height="100%">
      <div class="city_box">
        <topHeader>
          <div slot="center">
            <span>城市选择</span>
          </div>
          <div class="close" slot="right" @click="closeCity">
            &times;
          </div>
        </topHeader>
        <div class="city city-wap">
          <div class="search">
            <input type="text" placeholder="城市搜索" v-model="citySelect" @change="searchCity">
          </div>
          <div class="search_con">
            <div class="city_li" v-for="item of citySearchs" @click="choseOneCity(item.cityname)">{{ item.cityname }}</div>
          </div>
          <div class="city-list" ref="cityWarp">
            <div class="block-60"></div>
            <div v-for="item in cityListData" class="clearfix">
              <p :id="item.ckey">{{item.ckey}}</p>
              <ul>
                <li v-for="ritem in item.cityList" @click="choseOneCity(ritem.airportName)">{{ritem.airportName}}</li>
              </ul>
            </div>
          </div>
          <div class="filter">
            <div v-for="item in cityListKey" @click="switchKey(item)">{{item}}</div>
          </div>
          <div class="active-key" v-if="activeKey">{{activeKey}}</div>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>
/* eslint-disable */
import { loadPeopleFree, postCar, driverIdAuthority, driverCardAuthority, loadCitys, searchCity, unpayOrder } from '@/api/allapis'
import { Datetime, PopupPicker, Popup } from 'vux'
import topHeader from './../../components/topHeader'
import axios from 'axios'
export default {
  data () {
    return {
      agree: false,
      cityShow: false,
      cityType: null,
      postParam:{
        userId: null,
        start: '',
        end: '',
        roadline: '',
        outtime: '',
        motorType: '',
        freeSeat: '',
        cost: '',
        remark: '',
        name: ''
      },
      peopleNum: [],
      peopleNumList: [],
      startCity: '选择出发城市',
      endCity: '选择结束城市',
      routeTextarea: 'XX出发，途径X地铁站(推荐上车点)，X站上车，X站上高速，X站下高速，目的地：XX。',
      noteTextarea: '',
      carType: '',
      peopleMoney: [],
      peopleFreeList: [],
      activeKey: '',
      dataList: [],
      driverAuthority: false,
      driverCardAuthority: false,
      citySelect: '',
      citySearchs: []
    }
  },

  components: {
    Datetime,
    PopupPicker,
    topHeader,
    Popup
  },
  // beforeRouteEnter (to, from, next) {
  //   next((vm) => {
  //     vm.checkAccount()
  //   })
  // },
  computed: {
    cityListData(){
      let map = {}; // 处理过后的数据对象
      let temps = []; // 临时变量
      this.dataList.map(item=>{
          if(item.airportcode){
              let ekey = item.airportcode.charAt(0).toUpperCase(); // 根据key值的第一个字母分组，并且转换成大写
              temps = map[ekey] || []; // 如果map里面有这个key了，就取，没有就是空数组
              temps.push({
                  airportcode: item.airportcode,
                  airportName: item.cityname
              });
              map[ekey] = temps;
          }
      })
      let list = [];
      for(let gkey in map) {
          list.push({
              ckey: gkey,
              cityList: map[gkey]
          })
      }

      list = list.sort((li1, li2)=> li1.ckey.charCodeAt(0) - li2.ckey.charCodeAt(0));
      return list;
    },
    cityListKey(){
      let cityListKey = [];
      this.cityListData.map(item=>{
          cityListKey.push(item.ckey);
      })
      return cityListKey;
    }
  },
  created () {
    this.loadPeopleNumList()
    this.loadCityList()
    this.loadPeopleFree()
  },

  methods: {
    loadPeopleNumList () {
      let numList = []
      for(let i = 1; i <= 100; i++){
        numList.push(i)
      }
      this.peopleNumList.push(numList)
    },
    // checkAccount () {
    //   let params = {
    //     openid: this.$store.getters.getOpenid
    //   }
    //   checkAccount(params).then(res => {
    //     if (res.data === null) {
    //       this.$router.push({ name: 'telband' })
    //     }
    //   })
    // },
    choseCity (type) {
      this.citySearchs = []
      this.citySelect = ''
      this.cityType = type
      this.cityShow = true
    },
    loadCityList () {
      let self = this
      loadCitys().then(res => {
        self.dataList = res.data
      })
    },
    searchCity () {
      searchCity({name:this.citySelect}).then(res => {
        this.citySearchs = res.data
      })
    },
    switchKey(key){
      // 当前选中的字母
      this.activeKey = key;
      // 1秒后清空，让`active-key`隐藏
      setTimeout(()=>{
      this.activeKey = '';
      }, 1000)
      // 获取当前字母来cityList中距离顶部的位置
      let targetTop = document.querySelector('#'+key+'').offsetTop;
      console.log(targetTop)
      this.$nextTick(() => {
        console.log(this.$refs.cityWarp.scrollTop)
        this.$refs.cityWarp.scrollTop = targetTop-80
        // this.$refs.cityWarp.style.top = `-${targetTop}px`
      })
      // document.getElementById('cityWarp').scrollTop = 200
      // console.log(document.getElementById('city_warp'))
      // // window.scrollTo({ 
      //   top: targetTop - 100, // 60是search的高度
      //   behavior: "smooth" 
      // });
    },
    closeCity () {
      this.cityShow = false
    },
    choseOneCity (cityName) {
      this.peopleMoney = []
      if(this.cityType === 0) {
        this.cityShow = false
        this.startCity = cityName
      } else {
        this.cityShow = false
        this.endCity = cityName
      }
      if((this.startCity === '郑州' && this.endCity==='洛阳') || (this.startCity === '洛阳' && this.endCity==='郑州')){
        this.peopleMoney.push(50)
      }else if((this.startCity === '郑州' && this.endCity==='驻马店')||(this.startCity === '驻马店' && this.endCity==='郑州')){
        this.peopleMoney.push(80)
      }else if((this.startCity === '郑州' && this.endCity==='平顶山')||(this.startCity === '平顶山' && this.endCity==='郑州')){
        this.peopleMoney.push(50)
      }else if((this.startCity === '郑州' && this.endCity==='濮阳')||(this.startCity === '濮阳' && this.endCity==='郑州')){
        this.peopleMoney.push(60)
      }else if((this.startCity === '郑州' && this.endCity==='新密')||(this.startCity === '新密' && this.endCity==='郑州')){
        this.peopleMoney.push(20)
      }else if((this.startCity === '郑州' && this.endCity==='南阳')||(this.startCity === '南阳' && this.endCity==='郑州')){
        this.peopleMoney.push(100)
      }else if((this.startCity === '郑州' && this.endCity==='登封')||(this.startCity === '登封' && this.endCity==='郑州')){
        this.peopleMoney.push(40)
      }else if((this.startCity === '郑州' && this.endCity==='开封')||(this.startCity === '开封' && this.endCity==='郑州')){
        this.peopleMoney.push(30)
      }else if((this.startCity === '郑州' && this.endCity==='周口')||(this.startCity === '周口' && this.endCity==='郑州')){
        this.peopleMoney.push(50)
      }else if((this.startCity === '郑州' && this.endCity==='信阳')||(this.startCity === '信阳' && this.endCity==='郑州')){
        this.peopleMoney.push(100)
      }else if((this.startCity === '郑州' && this.endCity==='漯河')||(this.startCity === '漯河' && this.endCity==='郑州')){
        this.peopleMoney.push(50)
      }else if((this.startCity === '郑州' && this.endCity==='商丘')||(this.startCity === '商丘' && this.endCity==='郑州')){
        this.peopleMoney.push(60)
      }else if((this.startCity === '郑州' && this.endCity==='安阳')||(this.startCity === '安阳' && this.endCity==='郑州')){
        this.peopleMoney.push(60)
      }else if((this.startCity === '郑州' && this.endCity==='许昌')||(this.startCity === '许昌' && this.endCity==='郑州')){
        this.peopleMoney.push(50)
      }else if((this.startCity === '郑州' && this.endCity==='三门峡')||(this.startCity === '三门峡' && this.endCity==='郑州')){
        this.peopleMoney.push(80)
      }else if((this.startCity === '郑州' && this.endCity==='焦作')||(this.startCity === '焦作' && this.endCity==='郑州')){
        this.peopleMoney.push(40)
      }else if((this.startCity === '郑州' && this.endCity==='鹤壁')||(this.startCity === '鹤壁' && this.endCity==='郑州')){
        this.peopleMoney.push(50)
      }else if((this.startCity === '郑州' && this.endCity==='济源')||(this.startCity === '济源' && this.endCity==='郑州')){
        this.peopleMoney.push(60)
      }
    },
    async loadPeopleFree () {
      let freeList = []
      await loadPeopleFree().then(res => {
        if(res.data){
          res.data.forEach(elm => {
            freeList.push(elm.num)
          })
        }
      })
      this.peopleFreeList.push(freeList)
    },
    async sumit () {
      if(this.agree === true) {
        await driverIdAuthority({id: this.$store.state.user.uerInfo.id }).then(res => {
          if(res.data === '驾驶证已认证'){
            this.driverAuthority = true
          }
        })
        await driverCardAuthority({id: this.$store.state.user.uerInfo.id }).then(res => {
          if(res.data === '行驶证已认证'){
            this.driverCardAuthority = true
          }
        })
        console.log(this.$store.state.user.openid)
        unpayOrder({ openid: this.$store.state.user.openid }).then(res => {
          if(res.data === '已支付'){
            if(this.driverAuthority&&this.driverCardAuthority){
              if(this.startCity === '选择出发城市'){
                this.$vux.toast.show({
                  text: '请选择出发城市',
                  type: 'warn',
                  time: 800
                })
                return
              } else if(this.endCity === '选择结束城市') {
                this.$vux.toast.show({
                  text: '请选择结束城市',
                  type: 'warn',
                  time: 800
                })
                return
              } else if(this.postParam.outtime === ''){
                this.$vux.alert.show({
                  title: '人人同行提示',
                  content: '请选择出发时间',
                  buttonText: '好的',
                  hideOnBlur: true,
                  maskZIndex: 100
                })
                return
              }else if(this.postParam.freeSeat === ''){
                this.$vux.alert.show({
                  title: '人人同行提示',
                  content: '请选择乘坐人数',
                  buttonText: '好的',
                  hideOnBlur: true,
                  maskZIndex: 100
                })
                return
              }else if(this.routeTextarea === ''){
                this.$vux.alert.show({
                  title: '人人同行提示',
                  content: '请填写行驶路线',
                  buttonText: '好的',
                  hideOnBlur: true,
                  maskZIndex: 100
                })
                return
              }else if(this.carType === ''){
                this.$vux.alert.show({
                  title: '人人同行提示',
                  content: '请填写车型',
                  buttonText: '好的',
                  hideOnBlur: true,
                  maskZIndex: 100
                })
                return
              }else if(this.postParam.cost === ''){
                this.$vux.alert.show({
                  title: '人人同行提示',
                  content: '请选择分摊费用',
                  buttonText: '好的',
                  hideOnBlur: true,
                  maskZIndex: 100
                })
                return
              }
              this.postParam.userId = this.$store.state.user.uerInfo.id
              this.postParam.start = this.startCity
              this.postParam.end = this.endCity
              this.postParam.roadline = this.routeTextarea
              this.postParam.motorType = this.carType
              this.postParam.remark = this.noteTextarea
              this.postParam.name = this.$store.state.user.uerInfo.name
              console.log(this.postParam)
              postCar(this.postParam).then(res=>{
                // alert(res.data)
                console.log(res)
                this.$vux.alert.show({
                  title: '人人同行提示',
                  content: '发布成功',
                  buttonText: '好的',
                  hideOnBlur: true,
                  maskZIndex: 100
                })
                this.$router.push({ name: 'publishInfo', query: { orderId: res.data } })
              })
            }else{
              this.$vux.alert.show({
                title: '人人同行提示',
                content: '请先认证',
                buttonText: '好的',
                hideOnBlur: true,
                maskZIndex: 100
              })
              this.$router.push({ name: 'driverconfirm' })
            }
          } else {
            this.$vux.alert.show({
              title: '人人同行提示',
              content: '请尽快支付信息费',
              buttonText: '好的',
              hideOnBlur: true,
              maskZIndex: 100
            })
            this.$router.push({ name: 'myroute' })
          }
        })
      }else{
        this.$vux.toast.show({
          text: '请勾选用户协议',
          type: 'warn',
          time: 800
        })
        // alert('请勾选用户协议')
      }
    },
    OpenAbout () {
      this.$router.push({ name: 'article' })
    },
    changeTime (dateVal) {
      this.postParam.outtime = dateVal
    },
    onShow () {},
    onHide () {},
    onPeopleChange (val) {
      this.postParam.freeSeat = val.join('')
    },
    onFreeChange (val) {
      this.postParam.cost = val.join('')
    }
  }
}

</script>
<style lang='less' scoped>
@import url('./caruser.less');
</style>